<template>
  <div class="container">
    <el-row class="search">
      <el-col class="section-toolbar">
        <date-range-picker
          v-model="datePicker1"
          type="daterange"
          align="right"
          size="small"
          class="w-240"
          unlink-panels
          range-separator="~"
          :start-placeholder="$t('start_date')"
          :end-placeholder="$t('end_date')"
          value-format="yyyy-MM-dd"
          @change="timeChange"
        />
        <el-select v-model="listQuery.newsType" size="small" class="w-150">
          <el-option :value="null" :label="$t('all_information_types')" />
          <el-option
            v-for="(label, value) in newsTypeOpt"
            :key="value"
            :label="label"
            :value="value"
          />
        </el-select>
        <el-select v-model="listQuery.sourceType" size="small" class="w-150">
          <el-option :value="null" :label="$t('all_sources')" />
          <el-option
            v-for="(label, value) in newsSourceOpt"
            :key="value"
            :label="label"
            :value="value"
          />
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="search()"
          >{{ $t('search') }}</el-button
        >
      </el-col>
    </el-row>

    <el-row class="p-t-15">
      <el-col>
        <el-tabs ref="tabs" v-model="activeName" type="card">
          <el-tab-pane :label="$t('new_information')" name="first">
            <div class="title">
              <p>{{ $t('new_information') }}</p>
              <div class="btn">
                <el-button
                  class="fr m-l-10"
                  size="small"
                  @click="toExport('add')"
                >
                  {{ $t('export_doc') }}
                </el-button>
              </div>
            </div>
            <div class="echart">
              <div id="add" :style="{ width: '100%', height: '380px' }" />
            </div>
          </el-tab-pane>
          <el-tab-pane
            :label="$t('number_of_approved_information')"
            name="second"
          >
            <div class="title">
              <p>{{ $t('number_of_approved_information') }}</p>
              <div class="btn">
                <el-button
                  class="fr m-l-10"
                  size="small"
                  @click="toExport('pass')"
                  >{{ $t('export_doc') }}
                </el-button>
              </div>
            </div>
            <div class="echart">
              <div id="pass" :style="{ width: echartWidth, height: '380px' }" />
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import echarts from 'echarts';
import { dateShortcutKeyJS } from '@/mixins/index.js';
import timeUtils from '@/utils/timeHandle.js';
import { exportJsonToExcel, formatJson } from '@/utils/excel/Export2Excel';
import {
  increaseNewsNumApi,
  approveNewsNumApi
} from '@/api/information-content-analysis.js';
import '@/assets/css/common/style.scss';

const HeadWithOutWeek = {
  add: [
    {
      prop: 'date',
      label: 'time'
    },
    {
      prop: 'km',
      label: 'new_information_volume_in_cambodian'
    },
    {
      prop: 'zh',
      label: 'chinese_new_information'
    }
  ],
  pass: [
    {
      prop: 'date',
      label: 'time'
    },
    {
      prop: 'km',
      label: 'number_of_approved_news_in_cambodian'
    },
    {
      prop: 'zh',
      label: 'number_of_approved_information_in_chinese'
    }
  ]
};
export default {
  mixins: [dateShortcutKeyJS],

  data() {
    return {
      tableName: {
        add: this.$t('new_information'),
        pass: this.$t('number_of_approved_information')
      },
      tableHead: HeadWithOutWeek,
      activeName: 'first',
      newsTypeOpt: {
        1: this.$t('image_text'),
        2: this.$t('photo_album'),
        3: this.$t('video'),
        5: this.$t('micro_headlines'),
        8: this.$t('Short_video')
      },
      newsSourceOpt: {
        11: this.$t('reptile'),
        12: this.$t('background_editor'),
        13: this.$t('ordinary_members'),
        14: this.$t('ordinary_self_media'),
        15: this.$t('we_media_big_v')
      },
      datePicker1: [
        timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 6,
          'date'
        ),
        timeUtils.timeHandle(new Date().getTime(), 'date')
      ],
      listQuery: {
        newsType: null,
        sourceType: null,
        beginDate: timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 6,
          'date'
        ),
        endDate: timeUtils.timeHandle(new Date().getTime(), 'date'),
        time: 'day' // day, week, month
      },
      xData1: [], // 保存活跃用户实时分布x轴数据
      xData2: [], // 保存活跃阅读资讯人数x轴数据
      legend: {
        1: [this.$t('khmer'), this.$t('zh_hans')],
        2: [this.$t('khmer'), this.$t('zh_hans')]
      },
      list: {
        addKm: [], // 新增资讯柬文
        addZh: [], // 新增资讯柬文
        passKm: [], // 审核通过柬文
        passZh: [] // 审核通过中文
      },
      exportData: {
        // 导出表格数据
        add: [], // 新增资讯柬文
        pass: [] // 审核通过柬文
      },
      echartWidth: null,
      isFirstRender: true
    };
  },

  mounted() {
    this.getWidth();
    this.search();
  },

  methods: {
    timeChange(time) {
      if (!time) return;
      const startTime = Date.parse(time[0]);
      const endTime = Date.parse(time[1]);
      const Days = Math.floor(
        Math.abs(endTime - startTime) / (24 * 3600 * 1000)
      );
      if (Days <= 30) {
        this.listQuery.time = 'day';
      } else if (Days > 30 && Days <= 42) {
        this.listQuery.time = 'week';
      } else if (Days > 42) {
        this.listQuery.time = 'month';
      }
    },

    getWidth() {
      this.$nextTick(() => {
        this.echartWidth = `${this.$refs.tabs.$el.clientWidth}px`;
      });
    },

    getData1() {
      const myChart = echarts.init(document.getElementById('add'));
      myChart.showLoading();

      increaseNewsNumApi(this.listQuery).then(res => {
        if (res.code == 200) {
          const data = res.data || [];

          this.xData1 = [];
          this.list.addKm = [];
          this.list.addZh = [];

          this.exportData.add = data;

          for (let i = 0; i < data.length; i++) {
            this.xData1.push(data[i].date);
            this.list.addKm.push(data[i].km);
            this.list.addZh.push(data[i].zh);
          }

          this.updateEchart1();
        }
      });
    },

    updateEchart1() {
      const myChart = echarts.init(document.getElementById('add'));
      myChart.showLoading();

      const option = {
        color: this.$store.state.app.eChartColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: this.legend[1],
          right: 60,
          top: 10
        },
        grid: {
          left: 60,
          right: 60
        },
        xAxis: [
          {
            type: 'category',
            data: this.xData1
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: this.$t('khmer'),
            type: 'bar',
            stack: '广告',
            data: this.list.addKm
          },
          {
            name: this.$t('zh_hans'),
            type: 'bar',
            stack: '广告',
            data: this.list.addZh
          }
        ]
      };

      myChart.setOption(option, true);
      myChart.hideLoading();
    },

    getData2() {
      if (!this.isFirstRender) {
        const myChart = echarts.init(document.getElementById('pass'));
        myChart.showLoading();
      }

      approveNewsNumApi(this.listQuery).then(res => {
        if (res.code == 200) {
          const data = res.data || [];

          this.xData2 = [];
          this.list.passKm = [];
          this.list.passZh = [];

          this.exportData.pass = data;

          for (let i = 0; i < data.length; i++) {
            this.xData2.push(data[i].date);
            this.list.passKm.push(data[i].km);
            this.list.passZh.push(data[i].zh);
          }

          this.$nextTick(() => {
            this.updateEchart2();
          });
        }
      });
    },

    updateEchart2() {
      const myChart = echarts.init(document.getElementById('pass'));
      myChart.showLoading();

      const option = {
        color: this.$store.state.app.eChartColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: this.legend[1],
          right: 60,
          top: 10
        },
        grid: {
          left: 60,
          right: 60
        },
        xAxis: [
          {
            type: 'category',
            data: this.xData2
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: this.$t('khmer'),
            type: 'bar',
            stack: '广告',
            data: this.list.passKm
          },
          {
            name: this.$t('zh_hans'),
            type: 'bar',
            stack: '广告',
            data: this.list.passZh
          }
        ]
      };

      myChart.setOption(option, true);
      myChart.hideLoading();
      this.isFirstRender = false;
    },

    search() {
      if (!this.datePicker1) {
        this.$message.warning(this.$t('please_enter_a_search_time'), true);
        return;
      }
      const [beginDate, endDate] = this.datePicker1;
      this.listQuery.beginDate = beginDate;
      this.listQuery.endDate = endDate;

      this.getData1();
      this.getData2();
    },

    toExport(exportName) {
      const exprtTime = timeUtils.timeHandle(new Date().getTime(), 'date');
      const tHeader = this.tableHead[exportName].map(item =>
        this.$t(item.label)
      );
      const tKey = this.tableHead[exportName].map(item => item.prop);
      const data = formatJson(tKey, this.exportData[exportName]); // 数据格式化
      const fileName = this.tableName[exportName] + exprtTime;
      exportJsonToExcel(tHeader, data, fileName); // 导出文件
    }
  }
};
</script>
<style lang="scss" scoped>
.w-150 {
  width: 150px;
}
.title {
  height: 32px;
  position: relative;
  p {
    font-size: 22px;
    line-height: 32px;
    text-align: center;
  }
  .btn {
    width: 400px;
    height: 32px;
    position: absolute;
    right: 0;
    top: 0;
  }
}
</style>
